// import { LineType } from "klinecharts";
import i18n from "@/locals";
import { drawAction, drawEvent, drawPot, drawSignal, hitAction, hitCircle, hitPot, hitSignal, drawNews, drawStockSignal } from "./draw";
import { color } from "html2canvas/dist/types/css/types/color";
import { register } from "module";
const { init, registerOverlay, registerFigure, getFigureClass, getSupportedFigures, registerIndicator } = (window as any)["klinecharts"];
import { getFormatTime } from "@/components/chart/core/tooler";
import { formatBigNumber } from "@/comm/format";
const FALL_ICON = "/fall_icon.png";
const RISE_ICON = "/rise_icon.png";
const POT_ICON = "/pot.png";

const NEWS = "news";
const ACTION = "action";
const SIGNAL = "signal";
const STOCK_SIGNAL = "StockSignal";

const POT = "pot";
const Event = "event";
// const WAVE = "波动率";
const WAVE = i18n.global.t("message.Chart.f");
// const FUND_RATE = "资金费率";
const FUND_RATE = i18n.global.t("message.Chart.g");
const CHAIN_VOL = i18n.global.t("message.Indicator.table.j1");

const CHAIN_BUY = "CHAIN_BUY";
const CHAIN_SELL = "CHAIN_SELL";
export const CUSTOM_COLOR = "CUSTOM_COLOR";
const INFORMATION = "INFORMATION";
const VPVR = "VPVR";
const MVOL = 'MVOL';
let waveIdx = "";
let fundsIdx = "";
let chainVolIdx = "";
let kLine: { historyList: []; }
export async function initChartConfig(_kline?: any) {
    if (_kline) {
        kLine = _kline
    }

    const fall_img = await loadImg(FALL_ICON);
    const rise_img = await loadImg(RISE_ICON);
    const pot_img = await loadImg(POT_ICON);

    registerIndicator({
        name: WAVE,
        shortName: WAVE,
        precision: 7
    });

    registerIndicator({
        name: FUND_RATE,
        shortName: FUND_RATE,
        precision: 7
    });

    registerIndicator({
        name: "HBAR",
        shortName: ""
    });

    registerIndicator({
        name: CUSTOM_COLOR,
        shortName: CUSTOM_COLOR,
        draw: (params: any) => {
            console.log(CUSTOM_COLOR, params);
        }
    });

    registerIndicator({
        name: INFORMATION,
        shortName: " "
    });

    registerIndicator({
        name: VPVR,
        shortName: VPVR,
        calc: function (dataList: any[], indicator: any) {
            return dataList;
            // return dataList.map(function (kLineData, i) {
            //     return { high: kLineData.high };
            // });
        },
        draw: (param: any) => {
            // let { xAxis, yAxis, kLineDataList, ctx, indicator, visibleRange, bounding, barSpace } = param;
            // let list = indicator.result;
            // let { from, to } = visibleRange;
            // console.log(from, to, "f-t")
            // ctx.strokeStyle = "#ff0000";
            // ctx.lineWidth = 2;
            // ctx.fillStyle = "rgba(0, 0, 0, 0.4)";
            // let h = ctx.canvas.height / window.devicePixelRatio;
            // let width = 1;
            // let height = h * 0.6;
            // let x = ctx.canvas.width - width;
            // let y = h * 0.5 - height * 0.5;
            // ctx.fillStyle = "rgba(255, 0, 0, 0.3)";

            // let maxY = -Infinity;
            // let minY = Infinity;
            // for (let i = from; i < to; i++) {
            //     if(list[i].high > maxY) {
            //         maxY = list[i].high;
            //     }
            //     if(list[i].low < minY) {
            //         minY = list[i].low;
            //     }
            // }

            // let y1 = yAxis.convertToPixel(maxY);
            // let y2 = yAxis.convertToPixel(minY);
            // let len = y2 - y1;
            // let sp = len / 10;
            // for(let i = 0; i < 10; i++){
            //     ctx.fillRect(x, y1 + i * sp, width, len / 10 - 1);
            // }

            return false;
        }
    });

    registerIndicator({
        name: "TEST-Render",
        precision: 2,
        calc: function (kLineDataList: any[]) {
            return kLineDataList.map(kLineData => ({ volume: kLineData.volume }));
        },
        createTooltipDataSource: function (data: any) {
            return {
                name: "TEST-Render",
                values: [{ title: "VALUE: ", value: { text: data.crosshair.kLineData.volume, color: "rgb(65, 20, 69)" } }]
            };
        },
        draw: function (obj: any) {
            console.log("obj -- 24", obj);
            const { ctx, visibleRange, bounding, indicator } = obj;
            let max = 0;
            const result = indicator.result;
            for (let i = visibleRange.from; i < visibleRange.to; i++) {
                max = Math.max(max, result[i].volume);
            }
            const length = visibleRange.to - visibleRange.from;
            const barHeight = bounding.height / length;
            const realBarHeight = barHeight * 0.8;

            ctx.globalCompositeOperation = "destination-over";
            ctx.fillStyle = "rgba(65, 20, 69, .35)";
            let startY = (barHeight - realBarHeight) / 2;
            for (let i = visibleRange.from; i < visibleRange.to; i++) {
                const barWidth = Math.floor((result[i].volume / max) * 150);
                ctx.fillRect(bounding.width - barWidth, startY, barWidth, realBarHeight);
                startY += barHeight;
            }
        }
    });

    registerIndicator({
        name: MVOL,
        shortName: MVOL,
    });

    /*
    registerIndicator({
        name: MVOL,
        shortName: MVOL,
        shouldFormatBigNumber: true,
        calc: function (kLineDataList: any[], indicator: any) {
            // console.log(kLineDataList);
            let temp = kLineDataList.map((kLineData: any) => kLineData.volume);
            let max = Math.max(...temp);
            return kLineDataList.map(kLineData => ({ volume: kLineData.volume / max * 800 }));
        },
        figures: [
            {
                key: "volume",
                title: MVOL + ": ",
                type: "bar",
                baseValue: 0,
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    // console.log(data, "---")
                    const { open, close } = data.current.kLineData;
                    let color = "rgba(0,255,0,0.2)";
                    if (open > close) {
                        color = "rgba(255,0,0,0.2)";
                    }
                    const style = "fill";
                    return { style, color };
                }
            }
        ]
        // createTooltipDataSource: function (data:any) {
        //     let t = formatBigNumber(data.crosshair.kLineData.volume);
        //     return {
        //         name: MVOL,
        //         values: [{ title: 'VALUE: ', value: { text: t, color: 'rgb(255, 255. 255)' } }]
        //     }
        // },
        // draw: function (param:any) {
        //     const { ctx, visibleRange, bounding, indicator, kLineDataList, xAxis, yAxis, barSpace } = param;
        //     console.log(param);
        //     const {bar, gapBar, halfBar, halfGapBar} = barSpace;
        //     const {width, height} = bounding;
        //     const {from, to} = visibleRange;
        //     const tempAry = indicator.result.slice(from, to);
        //     const volumes = tempAry.map((i:any)=>i.volume);
        //     const maxVol = Math.max(...volumes);
        //     const minVol = Math.min(...volumes);
        //     ctx.fillStyle = 'rgba(0, 20, 255, .8)';
        //     for(let i = from; i < to; i++){
        //         let h =  1 || indicator.result[i].volume / maxVol * 150;
        //         let x = xAxis.convertTimestampToPixel(kLineDataList[i].timestamp);
        //         let y = height - h;
        //         ctx.fillRect(x - halfBar, y, bar, h);
        //     }

        // }
    })
    */

    registerIndicator({
        name: "CHAIN_BUY",
        shortName: i18n.global.t("message.Indicator.table.j1"),
        shouldFormatBigNumber: true,
        figures: [
            {
                key: "vol",
                title: CHAIN_BUY + ": ",
                type: "bar",
                baseValue: 0,
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    const { prev, current } = data;
                    const color = current.indicatorData.color;
                    const style = "fill";
                    return { style, color, borderColor: color };
                }
            },
            {
                key: "buy",
                title: i18n.global.t("message.charts.cb"),
            },
            {
                key: "sell",
                title: i18n.global.t("message.charts.cs"),
            },
            {
                key: "max",
                title: "max:",
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    return { color: "rgba(0,0,0,0)" };
                }
            }
        ],
        calc: (dataList: any[], indicator: any) => {
            let max = 0;
            let ary = dataList.map((kLineData: any, i: number) => {
                const macd: any = {};
                macd.buy = kLineData.buy?.inAmount || 0;
                macd.sell = kLineData.buy?.outAmount || 0;
                macd.vol = Math.abs(macd.buy) + Math.abs(macd.sell);
                macd.color = Math.abs(macd.buy) > Math.abs(macd.sell) ? "#29916f" : "#b82647";
                max = Math.max(max, macd.vol);
                return macd;
            });
            ary.forEach(i => {
                i.max = max;
                if (i.vol == 0) {
                    i.vol = max / 20;
                    i.color = "#2E3345";
                }
            });
            return ary;
        }
    });

    registerIndicator({
        name: "CHAIN_SELL",
        shortName: i18n.global.t("message.Indicator.table.j2"),
        shouldFormatBigNumber: true,
        figures: [
            {
                key: "vol",
                title: CHAIN_SELL + ": ",
                type: "bar",
                baseValue: 0,
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    const { prev, current } = data;
                    const color = current.indicatorData.color;
                    const style = "fill";
                    return { style, color, borderColor: color };
                }
            },
            {
                key: "buy",
                title: i18n.global.t("message.charts.ci"),
            },
            {
                key: "sell",
                title: i18n.global.t("message.charts.co"),
            },
            {
                key: "max",
                title: "max:",
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    return { color: "rgba(0,0,0,0)" };
                }
            }
        ],
        calc: (dataList: any[], indicator: any) => {
            console.log("### sell indicator calc")
            let max = 0;
            let ary = dataList.map((kLineData: any, i: number) => {
                const macd: any = {};
                macd.buy = kLineData.sell?.inAmount || 0;
                macd.sell = kLineData.sell?.outAmount || 0;
                macd.vol = Math.abs(macd.buy) + Math.abs(macd.sell);
                macd.color = macd.buy + macd.sell < 0 ? "#29916f" : "#b82647";
                max = Math.max(max, macd.vol);
                return macd;
            });
            ary.forEach(i => {
                i.max = max;
                if (i.vol == 0) {
                    i.vol = max / 20;
                    i.color = "#2E3345";
                }
            });
            return ary;
        }
    });

    registerIndicator({
        name: "BUY",
        // shortName: "净买入价值",
        shortName: i18n.global.t("message.Chart.chartB.a"),
        // calcParams: [12, 26, 9],
        calcParams: [6, 12, 4],
        shouldFormatBigNumber: true,
        figures: [
            {
                key: "buy",
                // title: "买入: ",
                title: i18n.global.t("message.Chart.chartB.b"),
                type: "bar",
                baseValue: 0,
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    const { prev, current } = data;
                    const color = "#2dc08e";
                    // const color = "rgba(0,0,0,0.2)";
                    const style = "fill";
                    return { style, color, borderColor: color };
                }
            },
            {
                key: "sell",
                // title: "卖出: ",
                title: i18n.global.t("message.Chart.chartB.c"),
                type: "bar",
                baseValue: 0,
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    const { prev, current } = data;
                    const color = "#f92855";
                    // const color = "rgba(0,0,0,0.2)";
                    const style = "fill";
                    return { style, color, borderColor: color };
                }
            },
            {
                key: "vol",
                // title: "净买入: ",
                title: i18n.global.t("message.Chart.chartB.d"),
                type: "line",
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    const { prev, current } = data;
                    const color = "#ffee58";
                    const style = "stroke";
                    return { style, color, borderColor: color, size: 2, borderStyle: "solid" };
                }
            }
        ],
        calc: (dataList: any[], indicator: any) => {
            return dataList.map((kLineData: any, i: number) => {
                const macd: any = {};
                macd.buy = kLineData.buy?.inAmount || 0;
                macd.sell = kLineData.buy?.outAmount || 0;
                macd.vol = macd.buy + macd.sell;
                macd.empty = macd.buy == 0 ? "buy" : "sell";
                // if(macd.buy != 0 || macd.sell != 0){
                //     console.log("you", macd, kLineData)
                // }
                return macd;
            });
        }
    });

    registerIndicator({
        name: "SELL",
        // shortName: "CEX净流出",
        shortName: i18n.global.t("message.Chart.chart.a"),
        calcParams: [12, 26, 9],
        shouldFormatBigNumber: true,
        figures: [
            {
                key: "buy",
                // title: "充值: ",
                title: i18n.global.t("message.Chart.chart.b"),
                type: "bar",
                baseValue: 0,
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    const { prev, current } = data;
                    const color = "#2dc08e";
                    const style = "fill";
                    return { style, color, borderColor: color };
                }
            },
            {
                key: "sell",
                // title: "提现: ",
                title: i18n.global.t("message.Chart.chart.c"),
                type: "bar",
                baseValue: 0,
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    const { prev, current } = data;
                    const color = "#f92855";
                    const style = "fill";
                    return { style, color, borderColor: color };
                }
            },
            {
                key: "vol",
                // title: "净流出: ",
                title: i18n.global.t("message.Chart.chart.d"),
                type: "line",
                baseValue: 0,
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    const { prev, current } = data;
                    const color = "#ffee58";
                    const style = "stroke";
                    return { style, color, borderColor: color, size: 2, borderStyle: "solid" };
                }
            }
        ],
        calc: (dataList: any[], indicator: any) => {
            // let max = 0;
            // dataList.forEach(i => {
            //     let t1 = Math.abs(i.sell?.inAmount || 0);
            //     let t2 = Math.abs(i.sell?.outAmount || 0);
            //     let t3 = Math.max(t1, t2);
            //     if (t3 > max) {
            //         max = t3;
            //     }
            // });
            // indicator.maxValue = max;
            // indicator.minValue = -max;
            // console.log("净流出----", indicator, "最大值", max);
            return dataList.map((kLineData: any, i: number) => {
                const macd: any = {};
                macd.buy = kLineData.sell?.inAmount || 0;
                macd.sell = kLineData.sell?.outAmount || 0;
                macd.vol = macd.buy + macd.sell;
                macd.empty = macd.buy == 0 ? "buy" : "sell";
                // if(macd.buy != 0 || macd.sell != 0){
                //     console.log("you", macd, kLineData)
                // }
                return macd;
            });
        }
    });

    registerIndicator({
        name: "EMA",
        shortName: "EMA",
        series: "price",
        calcParams: [6, 12, 20],
        precision: 2,
        shouldOhlc: true,
        figures: [
            {
                key: "ema1",
                title: "EMA6: ",
                type: "line",
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    const { prev, current } = data;
                    let color = "#0f0";
                    if (current.indicatorData?.ema1 < prev.indicatorData?.ema1) {
                        color = "#f92855";
                    }
                    const style = "stroke";
                    return { style, color, borderColor: color, size: 1, borderStyle: "solid" };
                }
            },
            {
                key: "ema2",
                title: "EMA12: ",
                type: "line",
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    const { prev, current } = data;
                    let color = "#0f0";
                    if (current.indicatorData?.ema2 < prev.indicatorData?.ema2) {
                        color = "#f92855";
                    }
                    const style = "stroke";
                    return { style, color, borderColor: color, size: 1, borderStyle: "solid" };
                }
            },
            {
                key: "ema3",
                title: "EMA20: ",
                type: "line",
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    const { prev, current } = data;
                    let color = "#0f0";
                    if (current.indicatorData?.ema3 < prev.indicatorData?.ema3) {
                        color = "#f92855";
                    }
                    const style = "stroke";
                    return { style, color, borderColor: color, size: 2, borderStyle: "solid" };
                }
            }
        ],
        regenerateFigures: (params: any[]) => {
            return params.map((p: number, i: number) => {
                return { key: `ema${i + 1}`, title: `EMA${p}: `, type: "line" };
            });
        },
        calc: (dataList: any[], indicator: any) => {
            // console.log(dataList,"dataListdataListdataListdataListdataListdataList")
            const { calcParams: params, figures } = indicator;
            let closeSum = 0;
            const emaValues: number[] = [];
            return dataList.map((kLineData: any, i: number) => {
                const ema: any = {};
                const close = kLineData.close;
                closeSum += close;
                // console.log(closeSum,"closeclosecloseclosecloseclose")
                params.forEach((p: number, index: number) => {
                    if (i >= p - 1) {
                        if (i > p - 1) {
                            emaValues[index] = (2 * close + (p - 1) * emaValues[index]) / (p + 1);
                        } else {
                            emaValues[index] = closeSum / p;
                        }
                        ema[figures[index].key] = emaValues[index];
                    }
                });
                return ema;
            });
        }
    });

    // 18根新线
    registerIndicator({
        name: "MORELINE",
        shortName: "MORELINE",
        series: "price",
        // calcParams: [5, 10, 15,20,25,30,35,40,45,50,55,60,65,70,75,80,200],
        precision: 2,
        shouldOhlc: true,
        figures: [
            {
                key: "ema1",
                title: "",
                type: "line",
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    const { prev, current } = data;
                    let color = "#0f0";
                    if (current.indicatorData?.ema1 < prev.indicatorData?.ema1) {
                        color = "#f92855";
                    }
                    const style = "stroke";
                    return { style, color, borderColor: color, size: 2, borderStyle: "solid" };
                }
            },
            {
                key: "ema2",
                title: "",
                type: "line",
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    const { prev, current } = data;
                    let color = "#0f0";
                    if (current.indicatorData?.ema2 < prev.indicatorData?.ema2) {
                        color = "#f92855";
                    }
                    const style = "stroke";
                    return { style, color, borderColor: color, size: 1, borderStyle: "solid" };
                }
            },
            {
                key: "ema3",
                title: "",
                type: "line",
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    const { prev, current } = data;
                    let color = "#0f0";
                    if (current.indicatorData?.ema3 < prev.indicatorData?.ema3) {
                        color = "#f92855";
                    }
                    const style = "stroke";
                    return { style, color, borderColor: color, size: 1, borderStyle: "solid" };
                }
            },
            {
                key: "ema4",
                title: "",
                type: "line",
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    const { prev, current } = data;
                    let color = "#0f0";
                    if (current.indicatorData?.ema4 < prev.indicatorData?.ema4) {
                        color = "#f92855";
                    }
                    const style = "stroke";
                    return { style, color, borderColor: color, size: 1, borderStyle: "solid" };
                }
            },
            {
                key: "ema5",
                title: "",
                type: "line",
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    const { prev, current } = data;
                    let color = "#0f0";
                    if (current.indicatorData?.ema5 < prev.indicatorData?.ema5) {
                        color = "#f92855";
                    }
                    const style = "stroke";
                    return { style, color, borderColor: color, size: 1, borderStyle: "solid" };
                }
            },
            {
                key: "ema6",
                title: "",
                type: "line",
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    const { prev, current } = data;
                    let color = "#0f0";
                    if (current.indicatorData?.ema6 < prev.indicatorData?.ema6) {
                        color = "#f92855";
                    }
                    const style = "stroke";
                    return { style, color, borderColor: color, size: 1, borderStyle: "solid" };
                }
            },
            {
                key: "ema7",
                title: "",
                type: "line",
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    const { prev, current } = data;
                    let color = "#0f0";
                    if (current.indicatorData?.ema7 < prev.indicatorData?.ema7) {
                        color = "#f92855";
                    }
                    const style = "stroke";
                    return { style, color, borderColor: color, size: 1, borderStyle: "solid" };
                }
            },
            {
                key: "ema8",
                title: "",
                type: "line",
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    const { prev, current } = data;
                    let color = "#0f0";
                    if (current.indicatorData?.ema8 < prev.indicatorData?.ema8) {
                        color = "#f92855";
                    }
                    const style = "stroke";
                    return { style, color, borderColor: color, size: 1, borderStyle: "solid" };
                }
            },
            {
                key: "ema9",
                title: "",
                type: "line",
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    const { prev, current } = data;
                    let color = "#0f0";
                    if (current.indicatorData?.ema9 < prev.indicatorData?.ema9) {
                        color = "#f92855";
                    }
                    const style = "stroke";
                    return { style, color, borderColor: color, size: 1, borderStyle: "solid" };
                }
            },
            {
                key: "ema10",
                title: "",
                type: "line",
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    const { prev, current } = data;
                    let color = "#0f0";
                    if (current.indicatorData?.ema10 < prev.indicatorData?.ema10) {
                        color = "#f92855";
                    }
                    const style = "stroke";
                    return { style, color, borderColor: color, size: 1, borderStyle: "solid" };
                }
            },
            {
                key: "ema11",
                title: "",
                type: "line",
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    const { prev, current } = data;
                    let color = "#0f0";
                    if (current.indicatorData?.ema11 < prev.indicatorData?.ema11) {
                        color = "#f92855";
                    }
                    const style = "stroke";
                    return { style, color, borderColor: color, size: 1, borderStyle: "solid" };
                }
            },
            {
                key: "ema12",
                title: "",
                type: "line",
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    const { prev, current } = data;
                    let color = "#0f0";
                    if (current.indicatorData?.ema12 < prev.indicatorData?.ema12) {
                        color = "#f92855";
                    }
                    const style = "stroke";
                    return { style, color, borderColor: color, size: 1, borderStyle: "solid" };
                }
            },
            {
                key: "ema13",
                title: "",
                type: "line",
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    const { prev, current } = data;
                    let color = "#0f0";
                    if (current.indicatorData?.ema13 < prev.indicatorData?.ema13) {
                        color = "#f92855";
                    }
                    const style = "stroke";
                    return { style, color, borderColor: color, size: 1, borderStyle: "solid" };
                }
            },
            {
                key: "ema14",
                title: "",
                type: "line",
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    const { prev, current } = data;
                    let color = "#0f0";
                    if (current.indicatorData?.ema14 < prev.indicatorData?.ema14) {
                        color = "#f92855";
                    }
                    const style = "stroke";
                    return { style, color, borderColor: color, size: 1, borderStyle: "solid" };
                }
            },
            {
                key: "ema15",
                title: "",
                type: "line",
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    const { prev, current } = data;
                    let color = "#0f0";
                    if (current.indicatorData?.ema15 < prev.indicatorData?.ema15) {
                        color = "#f92855";
                    }
                    const style = "stroke";
                    return { style, color, borderColor: color, size: 1, borderStyle: "solid" };
                }
            },
            {
                key: "ema16",
                title: "",
                type: "line",
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    const { prev, current } = data;
                    let color = "#0f0";
                    if (current.indicatorData?.ema15 < prev.indicatorData?.ema15) {
                        color = "#f92855";
                    }
                    const style = "stroke";
                    return { style, color, borderColor: color, size: 1, borderStyle: "solid" };
                }
            },
            {
                key: "ema17",
                title: "",
                type: "line",
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    const { prev, current } = data;
                    let color = "#0f0";
                    if (current.indicatorData?.ema15 < prev.indicatorData?.ema15) {
                        color = "#f92855";
                    }
                    const style = "stroke";
                    return { style, color, borderColor: color, size: 1, borderStyle: "solid" };
                }
            },
            {
                key: "ema18",
                title: "",
                type: "line",
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    const { prev, current } = data;
                    let color = "#0f0";
                    if (current.indicatorData?.ema16 < prev.indicatorData?.ema16) {
                        color = "#f92855";
                    }
                    const style = "stroke";
                    return { style, color, borderColor: color, size: 3, borderStyle: "solid" };
                }
            },
            {
                key: "ema19",
                title: "",
                type: "line",
                styles: (data: any, indicator: any, defaultStyles: any) => {
                    const { prev, current } = data;
                    let color = "#FCC235";
                    // if (current.indicatorData?.ema17 < prev.indicatorData?.ema17) {
                    //     color = "#f92855";
                    // }
                    const style = "stroke";
                    return { style, color, borderColor: color, size: 4, borderStyle: "solid" };
                }
            }
        ],
        regenerateFigures: (params: any[]) => {
            return params.map((p: number, i: number) => {
                // return { key: `ema${i + 1}`, title: `VPVR${p}: `, type: "line" };
                return { key: `ema${i + 1}`, title: `VPVR${p}: `, type: "line" };

            });
        },
        calc: (dataList: any[], indicator: any) => {
            let params = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 144]
            // let params = [5, 15,25,35,45,55,65,70,75,80,85,90,95,100,100,100,200]
            // let params = [5, 20,35,50,65,80,95,110,125,140,155,170,185,200,215,230,300]


            const { figures } = indicator;
            let closeSum = 0;
            const emaValues: number[] = [];

            return dataList.map((kLineData: any, i: number) => {
                const ema: any = {};
                const close = kLineData.close;
                closeSum += close;
                params.forEach((p: number, index: number) => {
                    if (i >= p - 1) {
                        if (i > p - 1) {
                            emaValues[index] = (2 * close + (p - 1) * emaValues[index]) / (p + 1);
                        } else {
                            emaValues[index] = closeSum / p;
                        }
                        ema[figures[index].key] = emaValues[index];
                    }
                });
                // kLineData.trend1=ema['ema18']

                // kLineData.trend2=ema['ema19']
                return ema;
            });

        }
    });

    registerFigure({
        name: POT,
        draw: function (ctx: any, attrs: any) {
            const { extendData } = attrs;
            if (extendData.visible) {
                drawPot(ctx, attrs.x, attrs.y, extendData.color);
            }
        },
        checkEventOn: (coordinate: any, attrs: any, styles: object) => {
            const { x, y } = coordinate;
            if (!attrs.extendData.visible) return false;
            if (hitPot(x, y, attrs)) {
                return true;
            }
            return false;
        }
    });

    registerFigure({
        name: SIGNAL,
        draw: function (ctx: any, attrs: any) {
            drawSignal(ctx, attrs.x, attrs.y, pot_img, attrs.extendData);
        },
        checkEventOn: (coordinate: any, attrs: any, styles: object) => {
            // console.warn(coordinate, attrs, styles, "00000")
            const { x, y } = coordinate;
            // const distance = hitSignal(x, y);
            if (hitSignal(x, y, attrs)) {
                // console.log("碰撞到 signal")
                return true;
            }
            return false;
        }
    });

    // 震荡信号
    registerFigure({
        name: STOCK_SIGNAL,
        draw: function (ctx: any, attrs: any) {
            drawStockSignal(ctx, attrs.x, attrs.y, pot_img, attrs.extendData);
        },
        checkEventOn: (coordinate: any, attrs: any, styles: object) => {
            // console.warn(coordinate, attrs, styles, "00000")
            const { x, y } = coordinate;
            // const distance = hitSignal(x, y);
            if (hitSignal(x, y, attrs)) {
                // console.log("碰撞到 signal")
                return true;
            }
            return false;
        }
    });

    registerFigure({
        name: ACTION,
        // zLevel: 4,
        draw: function (ctx: any, attrs: any) {
            const extendData = attrs.extendData;
            const { title, sub, num, action, icon, up } = extendData;
            let img = icon ? rise_img : fall_img;
            // console.log('注册action################', getFormatTime(attrs.extendData.origin.timestamp, 'yyyy-MM-dd hh:mm'), attrs.x, attrs.y)
            const rect = drawAction(ctx, { title, sub, num, action, up, extendData }, attrs.x, attrs.y, img);
            // console.log("我是Action的draw")
            // console.log(attrs.x, attrs.y)
            // console.log(attrs.x, attrs.y,"eventeventeventeventeventevent")

            // const rect = drawAction(ctx, { title, sub, up, extendData }, attrs.x, attrs.y, img);
            extendData.rect = rect;
        },
        checkEventOn: (coordinate: any, attrs: any, styles: object) => {
            // console.warn(coordinate, attrs, styles, "00000")
            const { x, y } = coordinate;
            const rect = attrs.extendData.rect;
            
            if (hitAction(x, y, rect)) {
                // console.log("碰撞到 action")
                return true;
            }
            return false;
        }
    });
    registerFigure({
        name: NEWS,
        totalStep: 1,
        draw: async function (ctx: any, attrs: any) {
            await drawNews(ctx, attrs.x, attrs.y);
        },
        checkEventOn: () => { }
    });
    registerFigure({
        name: Event,
        // zLevel: 1,
        draw: async function (ctx: any, attrs: any) {
            // console.log('注册event', attrs)
            const extendData = attrs.extendData;
            const { title, sub, num, action, icon, press } = extendData;
            let img = icon ? rise_img : fall_img;
            const rect = await drawEvent(ctx, { title, sub, num, action, press }, attrs.x, attrs.y, img);
            // console.log(attrs.x, attrs.y)

            extendData.rect = rect;
            // console.log("我是event的draw")
            // console.log("rect", rect);
        },
        checkEventOn: (coordinate: any, attrs: any, styles: object) => {
            // console.warn(coordinate, attrs, styles, "00000")
            const { x, y } = coordinate;
            const rect = attrs.extendData.rect;
            if (hitAction(x, y, rect)) {
                // console.log("碰撞到 event")
                return true;
            }
            return false;
        }
    });

    registerOverlay({
        name: SIGNAL,
        totalStep: 1,
        createPointFigures: (param: any) => {
            // console.log(param, "param")
            let { coordinates, overlay } = param;
            return {
                key: SIGNAL,
                type: SIGNAL,
                attrs: {
                    ...coordinates[0],
                    extendData: overlay.extendData
                },
                styles: {}
            };
        }
    });
    // 震荡信号
    registerOverlay({
        name: STOCK_SIGNAL,
        totalStep: 1,
        createPointFigures: (param: any) => {
            // console.log(param, "param")
            let { coordinates, overlay } = param;
            return {
                key: STOCK_SIGNAL,
                type: STOCK_SIGNAL,
                attrs: {
                    ...coordinates[0],
                    extendData: overlay.extendData
                },
                styles: {}
            };
        }
    });

    registerOverlay({
        name: ACTION,
        totalStep: 1,
        zLevel: 999,
        createPointFigures: (param: any) => {
            return {
                key: ACTION,
                type: ACTION,
                attrs: {
                    ...param.coordinates[0],
                    extendData: param.overlay.extendData
                }
            };
        }
    });

    registerOverlay({
        name: POT,
        totalStep: 1,
        createPointFigures: (param: any) => {
            return {
                key: POT,
                type: POT,
                attrs: {
                    ...param.coordinates[0],
                    extendData: param.overlay.extendData
                }
            };
        }
    });

    registerOverlay({
        name: NEWS,
        totalStep: 1,
        createPointFigures: (param: any) => {
            return {
                key: NEWS,
                type: NEWS,
                attrs: {
                    ...param.coordinates[0]
                }
            };
        }
    });
    registerOverlay({
        name: Event,
        totalStep: 1,
        zLevel: -10,
        createPointFigures: (param: any) => {
            return {
                key: Event,
                type: Event,
                attrs: {
                    ...param.coordinates[0],
                    extendData: param.overlay.extendData
                }
            };
        }
    });

    registerOverlay({
        name: ACTION,
        totalStep: 1,
        // zLevel: 30,
        createPointFigures: (param: any) => {
            return {
                key: ACTION,
                type: ACTION,
                attrs: {
                    ...param.coordinates[0],
                    extendData: param.overlay.extendData
                }
            };
        }
    });
}

function loadImg(src: string) {
    return new Promise(resolve => {
        const img = new Image();
        img.onload = () => {
            resolve(img);
        };
        img.src = src;
    });
}

export const createWaveIndicator = (chart: any) => {
    waveIdx = chart.createIndicator({
        name: WAVE,
        shortName: WAVE,
        figures: [{ key: "ao", title: WAVE + ": ", type: "line" }],
        calc: function (dataList: any[], indicator: any) {
            return dataList.map(function (kLineData, i) {
                const ao = ((kLineData.high - kLineData.low) / kLineData.high + (kLineData.high - kLineData.low) / kLineData.low) / 2;
                return { ao: ao * 100 };
            });
        },
        draw: (param: any) => {
            // console.log(param, "draw bar");
            let { xAxis, yAxis, kLineDataList, ctx, indicator, visibleRange, bounding, barSpace } = param;
            let list = indicator.result;
            let { from, to } = visibleRange;
            // ctx.fillStyle = "#f0f0f0";
            ctx.fillRect(0, 0, bounding.width, bounding.height);
            ctx.strokeStyle = "#ff0000";
            ctx.lineWidth = 2;
            ctx.setLineDash([]);
            for (let i = from; i < to; i++) {
                let x = xAxis.convertTimestampToPixel(kLineDataList[i].timestamp);
                let y = yAxis.convertToPixel(list[i].ao) + 4;
                if (i == from) {
                    ctx.moveTo(x, y);
                } else {
                    ctx.lineTo(x, y);
                }
            }

            ctx.stroke();

            ctx.fillStyle = "#005566";
            for (let i = from; i < to; i++) {
                let x = xAxis.convertTimestampToPixel(kLineDataList[i].timestamp);
                let y = yAxis.convertToPixel(list[i].ao) + 4;
                ctx.fillRect(x - barSpace.halfBar / 2, y, barSpace.halfBar, bounding.height - y);
            }

            return false;
        }
    });
    return waveIdx;
};

export const removeWaveIndicator = (chart: any) => {
    chart.removeIndicator(waveIdx);
};

export const createFundRateIndicator = (chart: any) => {
    fundsIdx = chart.createIndicator({
        name: FUND_RATE,
        shortName: FUND_RATE,
        figures: [{ key: "rate", title: FUND_RATE + ": ", type: "line" }],
        calc: (dataList: any[], indicator: any) => {
            return dataList.map((kLineData, i: number) => {
                const emv: any = {
                    rate: kLineData.fundingRate * 100 || 0
                };
                return emv;
            });
        },
        draw: (param: any) => {
            // console.log("param", param);
            // const {ctx, kLineDataList, xAxis, yAxis} = param;
            // let pots = kLineDataList.map((i:any)=>{
            //     return {
            //         x: xAxis.convertTimestampToPixel(i.timestamp),
            //         y: yAxis.convertToPixel(i.close),
            //     }
            // })

            // ctx.strokeStyle = '#fcc235';
            // ctx.lineWidth = 2;
            // ctx.setLineDash([]);

            // ctx.beginPath();
            // for(let i = 0; i < pots.length; i++){
            //     if(i == 0){
            //         ctx.moveTo(pots[i].x, pots[i].y);
            //     }
            //     else{
            //         ctx.lineTo(pots[i].x, pots[i].y);
            //     }
            // }
            // ctx.stroke();
            // true, {id: 'candle_pane'}
            return false;
        }
    });

    return fundsIdx;
};

export const removeFundRateIndicator = (chart: any) => {
    chart.removeIndicator(fundsIdx);
};

export const createCustomColorIndicator = (chart: any) => {
    fundsIdx = chart.createIndicator({
        name: CUSTOM_COLOR,
        shortName: CUSTOM_COLOR,
        figures: [{ key: "rate", title: CUSTOM_COLOR + ": ", type: "line" }],
        calc: (dataList: any[], indicator: any) => {
            // return dataList.map((kLineData, i: number) => {
            //     const emv: any = {
            //         rate: kLineData.fundingRate * 100 || 0
            //     };
            //     return emv;
            // });
            return dataList;
        }
    });
    return fundsIdx;
};

export const addCloseBtn = (chart: any, id: string, callback: Function) => {
    const dom: any = document.getElementById(id);
    const close = document.createElement("div");
    close.classList.add("id-close");
    close.onclick = () => {
        console.log("close");
        chart.removeIndicator(id);
        callback();
    };
    dom.onmouseover = () => {
        close.style.opacity = "1";
    };
    dom.onmouseout = () => {
        close.style.opacity = "0";
    };
    dom.appendChild(close);
};

// export const createChainVolIndicator = (chart: any) => {
//     chainVolIdx = chart.createIndicator({
//         name: "CHAIN_VOL",
//         shortName: CHAIN_VOL,
//         figures: [{ key: "rate", title: CHAIN_VOL + ": ", type: "line" }],
//         calc: (dataList: any[], indicator: any) => {
//             return dataList.map((kLineData: any, i: number) => {
//                 const macd: any = {};
//                 macd.buy = kLineData.sell?.inAmount || 0;
//                 macd.sell = kLineData.sell?.outAmount || 0;
//                 macd.vol = macd.buy + macd.sell;
//                 macd.empty = macd.buy == 0 ? "buy" : "sell";
//                 return macd;
//             });
//         }
//     });
//     return chainVolIdx;
// };

// export const removeChainVolIndicator = (chart:any)=>{
//     chart.removeIndicator(chainVolIdx);
// }
